package com.example.util;

import org.apache.commons.lang3.StringUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;

/**
 * 字符串工具类
 */
public class StringUtil extends StringUtils {

    /**
     * 将所给字符串按所给的seperator split成Long数组.示例：
     * splitToLong("1,2,3",",")后得到ArrayList.
     *
     * @param string
     * @param separator
     * @return
     */
    public static ArrayList<Long> splitToLong(String string, String separator) {
        checkNull(string, "str");
        checkEmpty(separator, "separator");
        String[] strArray = string.split(separator);
        ArrayList<Long> list = new ArrayList<Long>();
        Long[] result = new Long[strArray.length];
        for (int i = 0; i < result.length; i++) {
            if (!isEmpty(strArray[i])) {
                list.add(Long.valueOf(strArray[i]));
            }
        }
        return list;
    }

    /**
     * 判断是否为long类型
     */
    public static boolean isLong(Long num) {
        return ((null == num) || num < 0L);
    }

    /**
     * 检查所给的字符串是否为空. 字符串为空是指字符串为null或者str.trim().length为0.
     *
     * @param str     被检查的参数
     * @param strName 被检查的参数名称
     * @throws IllegalArgumentException 如果字符串为空
     */
    public static void checkEmpty(String str, String strName) {
        checkNull(str, strName);
        if (str.trim().length() == 0) {
            throw new IllegalArgumentException("String with name " + strName + " can not be empty");
        }
    }

    /**
     * 检查所给的对象是否为null.
     *
     * @param obj     被检查的对象
     * @param objName 被检查的对象名称
     * @throws IllegalArgumentException 如果所给参数为null.
     */
    public static void checkNull(Object obj, String objName) {
        if (obj == null) {
            throw new IllegalArgumentException("Object with name " + objName + " can not be null");
        }
    }

    /**
     * 格式化大小
     *
     * @param size
     * @return
     */
    public static String formatSize(long size) {

        if (size / (1024 * 1024) > 0) {
            float tmpSize = (float) (size) / (float) (1024 * 1024);
            DecimalFormat df = new DecimalFormat("#.##");
            return "" + df.format(tmpSize) + "MB";
        } else if (size / 1024 > 0) {
            return "" + (size / (1024)) + "KB";
        } else {
            return "" + size + "B";
        }
    }
}
